﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Approval.Infrastructure
{
    public class BaseRepsitory<T> : IBaseRepository<T> where T : class
    {
        private readonly MyDbContext db;

        public BaseRepsitory(MyDbContext db)
        {
            this.db = db;
        }

        public async Task<IQueryable<T>> All()
        {
            return await Task.FromResult(db.Set<T>().AsQueryable());
        }

        public async Task<int> Create(T model)
        {
            await db.AddAsync(model);
            return await db.SaveChangesAsync();
        }

        public async Task<int> Delete(int id)
        {
            DbSet<T> dbset = db.Set<T>();
            var res = dbset.Find(id);
            dbset.Remove(res);
            return await db.SaveChangesAsync();
        }

        public async Task<int> DeleteInfo(Expression<Func<T, bool>> info)
        {
            DbSet<T> dbset = db.Set<T>();
            var res = dbset.Where(info);
            dbset.RemoveRange(res);
            return await db.SaveChangesAsync();
        }

        public async Task<T> GetInfo(Expression<Func<T, bool>> info)
        {
            DbSet<T> dbset = db.Set<T>();
            return await dbset.FirstOrDefaultAsync(info);
        }

        public async Task<T> Get(int id)
        {
            DbSet<T> dbset = db.Set<T>();
            return await dbset.FindAsync(id);
        }

        public async Task<List<T>> GetList()
        {
            return await db.Set<T>().AsNoTracking().ToListAsync();
        }

        public async Task<List<T>> GetListInfo(Expression<Func<T, bool>> info)
        {
            return await db.Set<T>().Where(info).ToListAsync();
        }

        public async Task<int> Update(T model)
        {
            DbSet<T> dbset = db.Set<T>();
            dbset.Update(model);
            return await db.SaveChangesAsync();
        }

        public async Task<int> DeleteList(IQueryable<T> info)
        {
            db.Set<T>().RemoveRange(info);
            return await db.SaveChangesAsync();
        }

        public async Task<int> UpdateRange(List<T> info)
        {
            db.Set<T>().UpdateRange(info);
            return await db.SaveChangesAsync();
        }
    }
}
